#!/bin/sh
#
# We need to be sure pmcd is stable before creating any of the QA
# archives.
#
# In particular any post-install .Need* files have been dealt with
# as these may cause various pmcd state changes that can be reflected
# in <mark> record badness in the archives created by pmlogger.
#

. ${PCP_CONF:-/etc/pcp.conf}

# need this for pmsleep
#
export PATH=$PCP_BINADM_DIR:$PATH

tmp=/var/tmp/check-pmcd-stable-$$
sts=0
trap "rm -f $tmp.*; exit \$sts" 0 1 2 3 15

_check()
{
    find $PCP_PMDAS_DIR -name ".Need*" -print \
    | while read f
    do
	case "$f"
	in
	    *.failed)
		# Install/Remove failed, cannot have further concurrent
		# actions unless pmcd restart is done (again)
		#
		;;
	    *)
		echo $f
		;;
	esac
    done
}

# emasculated version of _service() from ../common.check ...
#
_restart_pmcd()
{
    if [ "$PCPQA_SYSTEMD" = yes ]
    then
	sudo systemctl restart pmcd.service
    elif [ -f $PCP_RC_DIR/pmcd ]
    then
	sudo $PCP_RC_DIR/pmcd restart
    else
	echo "_restart_pmcd: pmcd not a systemctl service nor a $PCP_RC_DIR script!"
	sts=1
	exit
    fi
}

_check >$tmp.tmp
if [ -s $tmp.tmp ]
then
    echo "Need to wait while these get fixed: `tr '\012' ' ' <$tmp.tmp`"
    [ -f $PCP_LOG_DIR/NOTICES ] && cp $PCP_LOG_DIR/NOTICES $tmp.NOTICES
    if [ -f $PCP_TMPFILE_DIR/pmda.auto.update ]
    then
	# pmcd restart is already in progress, just wait for auto
	# Install/Remove operations to complete
	#
	:
    else
	# Get pmcd going ...
	#
	_restart_pmcd
    fi
    i=0
    rm -f $tmp.ok
    # give the rc scripts $wait seconds to get going and poll every
    # $poll milliseconds
    #
    wait=120
    poll=250
    iter=`expr $wait \* 1000 / $poll`
    while [ $i -lt $iter ]
    do
	pmsleep ${poll}msec
	_check >$tmp.tmp
	if [ -s $tmp.tmp ]
	then
	    :
	else
	    touch $tmp.ok
	    break
	fi
	i=`expr $i + 1`
    done
    if [ -f $tmp.ok ]
    then
	# whack pmcd to be sure, to be sure, ...
	#
	pminfo -v >/dev/null 2>&1
    else
	echo "Failed to fix these after ${wait}secs: `tr '\012' ' ' <$tmp.tmp`"
	echo "at `date`"
	echo "Recent changes to NOTICES ..."
	[ -f $PCP_LOG_DIR/NOTICES ] && diff $tmp.NOTICES $PCP_LOG_DIR/NOTICES
	echo "pmcd-related processes ..."
	$PCP_PS_PROG $PCP_PS_ALL_FLAGS | grep -E '[P]PID|[p]mcd'
	sts=1
    fi
fi
